package com.zhengsr.latte.ui.recycler;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * Created by zhengshaorui on 2018/5/27.
 */

public class DataConverter {
    private static final String TAG = "DataConverter";
    //用一个queue，防止数据过大崩溃
    private static  ReferenceQueue<LinkedHashMap<Object,Object>> ITEM_QUEUE = new ReferenceQueue<>();
    private static  LinkedHashMap<Object,Object> MULTIPLE_FIELDS = new LinkedHashMap<>();
    //用软引用
    private static  SoftReference<LinkedHashMap<Object,Object>> FIELDS_REFERENCE = new
            SoftReference<>(MULTIPLE_FIELDS,ITEM_QUEUE);
    private DataConverter(){
    }

    public static DataConverter creat(){
        return new DataConverter();
    }


    public List<MultipleBean> getDataConver(String json){
        JSONArray datas = JSONObject.parseObject(json).getJSONArray("data");
        final List<MultipleBean> multipleList = new ArrayList<>();
        int count = datas.size();
        for (int i = 0; i < count; i++) {
            final JSONObject data = datas.getJSONObject(i);
            final String imageUrl = data.getString("imageUrl");
            final String text = data.getString("text");
            final int spanSize = data.getInteger("spanSize");
            final int id = data.getInteger("goodsId");
            final JSONArray banners = data.getJSONArray("banners");
            int type = 0;
            List<String> bannerImages = new ArrayList<>();
            if (imageUrl != null && text != null){
                type = ItemType.TYPE_IMAGE_TEXT;
            }else if (imageUrl != null){
                type = ItemType.TYPE_IMAGE;
            }else if( text != null){
                type = ItemType.TYPE_TEXT;
            }else if (banners != null){
                type = ItemType.TYPE_BANNER;
                int size = banners.size();
                for (int j = 0; j < size; j++) {
                    String bannerUrl = banners.getString(j);
                    bannerImages.add(bannerUrl);

                }
            }

            MultipleBean bean = new MultipleBuilder.Builder()
                    .setField(MultipleConfig.ITEM_TYPE,type)
                    .setField(MultipleConfig.SPAN_SIZE,spanSize)
                    .setField(MultipleConfig.ID,id)
                    .setField(MultipleConfig.IMAGE_URL,imageUrl)
                    .setField(MultipleConfig.TEXT,text)
                    .setField(MultipleConfig.BANNERS,bannerImages)
                    .builder();

            multipleList.add(bean);

        }

        return  multipleList;
    }

}
